package com.winhxd.b2c.product.service.impl;

import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.domain.product.condition.ProductCategoryCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductCategorySaveCondition;
import com.winhxd.b2c.common.domain.product.model.ProductCategory;
import com.winhxd.b2c.common.domain.product.model.ProductSpuCategory;
import com.winhxd.b2c.common.domain.product.vo.ProductCategoryVO;
import com.winhxd.b2c.common.domain.product.vo.ProductQueryWithCategoryVO;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.product.dao.ProductCategoryMapper;
import com.winhxd.b2c.product.dao.ProductSpuCategoryMapper;
import com.winhxd.b2c.product.service.ProductCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;


/**
 * @author luosixiang
 */
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    private Logger logger = LoggerFactory.getLogger(ProductCategoryServiceImpl.class);

    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private ProductSpuCategoryMapper productSpuCategoryMapper;

    @Override
    public List<ProductCategoryVO> findAllCategory()
    {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setLevel((byte) 1);
        List<ProductCategory> productCategoriesFirst = productCategoryMapper.selectByModel(productCategory);
        List<ProductCategoryVO> productCategoryVOList = new ArrayList<>();
        if(CollectionUtils.isEmpty(productCategoriesFirst)){
            return productCategoryVOList;
        }
        for (int i = 0;i < productCategoriesFirst.size();i++){
            productCategory.setLevel((byte) 2);
            productCategory.setParentId(productCategoriesFirst.get(i).getId());
            ProductCategoryVO productCategoryVO = new ProductCategoryVO();
            BeanUtils.copyProperties(productCategoriesFirst.get(i),productCategoryVO);
            List<ProductCategory> productCategoriesSecond = productCategoryMapper.selectByModel(productCategory);
            if (!CollectionUtils.isEmpty(productCategoriesSecond)){
                productCategoryVO.setSecondCategoryList(productCategoriesSecond);
            }else {
                productCategoriesSecond = new ArrayList<ProductCategory>();
                productCategoryVO.setSecondCategoryList(productCategoriesSecond);
            }
            productCategoryVOList.add(productCategoryVO);
        }
        logger.info("查询所有商品分类返回结果:"+JsonUtil.toJSONString(productCategoryVOList));
        return productCategoryVOList;
    }

    @Override
    public Integer addProductCategory(ProductCategoryVO productCategoryVO) {
        if (null == productCategoryVO){
            return 0;
        }
        ProductCategory productCategory = new ProductCategory();
        BeanUtils.copyProperties(productCategoryVO,productCategory);
        return productCategoryMapper.insertSelective(productCategory);
    }

    @Override
    public Integer modifyProductCategory(ProductCategoryVO productCategoryVO) {
        if (null == productCategoryVO){
            return 0;
        }
        ProductCategory productCategory = new ProductCategory();
        BeanUtils.copyProperties(productCategoryVO,productCategory);
        return productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    @Override
    public Integer deleteProductCategory(ProductCategoryVO productCategoryVO) {
        if (null == productCategoryVO){
            return 0;
        }
        return productCategoryMapper.deleteByPrimaryKey(productCategoryVO.getId());
    }

    @Override
    public Boolean isCandeleteProductCategory(Long categoryId) {
        return null;
    }

    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_COMMITTED)
    @Override
    public List<ProductCategoryVO> saveProductCategory(ProductCategorySaveCondition condition) {
        logger.info("保存商品分类入参:"+JsonUtil.toJSONString(condition));
        if (ObjectUtils.isEmpty(condition) || CollectionUtils.isEmpty(condition.getProductCategoryConditionList())) {
            logger.info("商品分类数据入参为空");
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        List<ProductCategoryCondition> productCategoryConditionList = condition.getProductCategoryConditionList();
        for (int i = 0;i < productCategoryConditionList.size();i++) {
            //操作一级分类
            Long id = operateProductCategoryData(productCategoryConditionList.get(i),condition.getUserName());
            //操作二级分类
            if (!CollectionUtils.isEmpty(productCategoryConditionList.get(i).getSecondCategoryList())){
                for (int j = 0;j < productCategoryConditionList.get(i).getSecondCategoryList().size();j++){
                    ProductCategoryCondition productCategoryCondition = new ProductCategoryCondition();
                    BeanUtils.copyProperties(productCategoryConditionList.get(i).getSecondCategoryList().get(j),productCategoryCondition);
                    if (id != -1){
                        productCategoryCondition.setParentId(id);
                    }
                    operateProductCategoryData(productCategoryCondition,condition.getUserName());
                }
            }
        }
        return findAllCategory();
    }

    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_COMMITTED)
    @Override
    public Boolean checkAndDeleteProductCategory(ProductCategoryCondition condition) {
        logger.info("检查并删除商品分类入参:"+JsonUtil.toJSONString(condition));
        if (null == condition) {
            logger.info("检查商品分类是否可以删除接口入参为空");
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        Boolean res = false;
        if (condition.getLevel() == 1){
            ProductSpuCategory productSpuCategory = new ProductSpuCategory();
            productSpuCategory.setCategoryOneId(condition.getId());
            List<ProductSpuCategory> productSpuCategories = productSpuCategoryMapper.selectByModel(productSpuCategory);
            if (productSpuCategories.size() != 0) {
                throw new BusinessException(BusinessCode.CODE_820501);
            }else {
                this.deleteProductCategoryById(condition.getId());
                res = true;
            }
        }else if (condition.getLevel() == 2){
            ProductSpuCategory productSpuCategory = new ProductSpuCategory();
            productSpuCategory.setCategoryTwoId(condition.getId());
            List<ProductSpuCategory> productSpuCategories = productSpuCategoryMapper.selectByModel(productSpuCategory);
            if (productSpuCategories.size() != 0) {
                throw new BusinessException(BusinessCode.CODE_820501);
            }else {
                this.deleteProductCategoryById(condition.getId());
                res = true;
            }
        }

        return res;
    }

    /**
     * 根据条件判断是新增修改还是删除
     * @author luosixiang
     * @date 16:16 2019/1/7
     * @param username
     * @return Long
     **/
    private Long operateProductCategoryData(ProductCategoryCondition condition,String username){
        Long result = -1L;
        //id为空  新增  id不为空删除状态为0为修改  id不为空删除状态为1为删除
        if (ObjectUtils.isEmpty(condition.getId())){
            ProductCategory productCategory = new ProductCategory();
            BeanUtils.copyProperties(condition,productCategory);
            productCategory.setCreatedBy(username);
            productCategory.setCreatedTime(new Date());
            productCategory.setModifiedBy(username);
            productCategory.setModifiedTime(new Date());
            productCategory.setStatus(1);
            productCategoryMapper.insertSelective(productCategory);
            result = productCategory.getId();
        }else if (!ObjectUtils.isEmpty(condition.getId())){
            ProductCategory productCategory = new ProductCategory();
            BeanUtils.copyProperties(condition,productCategory);
            productCategory.setModifiedBy(username);
            productCategory.setModifiedTime(new Date());
            productCategoryMapper.updateByPrimaryKeySelective(productCategory);
        }
        return result;
    }

    private void deleteProductCategoryById(Long id){
        ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(id);
        if (null == productCategory){
            logger.info("要删除的分类不存在,无法删除");
        }else{
            if (productCategory.getLevel() == 1){
                //如果当前要删除的分类为一级分类，则查出它所包括的所有二级分类并删除
                ProductCategory condition = new ProductCategory();
                condition.setParentId(id);
                List<ProductCategory> productCategoryList = productCategoryMapper.selectByModel(condition);
                if (!CollectionUtils.isEmpty(productCategoryList)){
                    for (ProductCategory pc:productCategoryList) {
                        productCategoryMapper.deleteByPrimaryKey(pc.getId());
                    }
                }
                productCategoryMapper.deleteByPrimaryKey(id);
            }else {
                //不是一级分类，直接删除
                productCategoryMapper.deleteByPrimaryKey(id);
            }
        }
    }

    @Override
    public List<ProductCategory> findProductCategoryByModel(ProductCategoryCondition condition) {
        logger.info("根据model查询商品分类入参:"+JsonUtil.toJSONString(condition));
        if (ObjectUtils.isEmpty(condition)){
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        ProductCategory productCategory = new ProductCategory();
        BeanUtils.copyProperties(condition,productCategory);
        return productCategoryMapper.selectByModel(productCategory);
    }

}
